import { _decorator, color, Component, Graphics, log, Node, Vec3 } from 'cc';
const { ccclass, property,executeInEditMode ,float} = _decorator;

/**
 * 闪电效果组件，用于绘制闪电效果。
 * 中点位移算法实现2D 闪电链
 * https://krazydad.com/bestiary/bestiary_lightning.html

 */
@ccclass('Flash')
@executeInEditMode(true)
export class Flash extends Component {

    @property(Node)
    pos1:Node

    @property(Node)
    pos2:Node

    /**
     * 最小的闪电位移量，用于控制闪电的弯曲程度。数值越小，闪电越直；数值越大，闪电越弯曲。

     */
    @float
    detail:number

    /**
     * 闪电的横向和纵向的位移量，数值越大，位置随机范围越大，闪电越弯曲，
     */
    @float
    displace:number

    graf:Graphics
    start() {
        this.graf = this.node.getComponent(Graphics)
        // this.schedule(this.startDraw,0.1)
    }

    update(deltaTime: number) {
        this.graf.clear()
        this.drawLightning(this.pos1.position.x,this.pos1.position.y,this.pos2.position.x,this.pos2.position.y,this.displace)
        this.graf.stroke()
    }

    startDraw() {
        this.graf.clear()
        this.graf.lineWidth = 10
        // this.graf.strokeColor = color(255,0,0, 255)
        console.log(1);
        
        // this.graf.moveTo(this.pos1.position.x,this.pos1.position.y)
        // this.graf.lineTo(this.pos2.position.x,this.pos2.position.y)
        // this.graf.stroke()

        this.drawLightning(this.pos1.position.x,this.pos1.position.y,this.pos2.position.x,this.pos2.position.y,this.displace)
        this.graf.stroke()
    }

    drawLightning(x1:number,y1:number,x2:number,y2:number,displace:number)
    {
        if (displace < this.detail) {
            this.graf.moveTo(x1,y1);
            this.graf.lineTo(x2,y2);
        }
        else {
            var mid_x = (x2+x1)/2;
            var mid_y = (y2+y1)/2;
            mid_x += (Math.random()-.5)*displace;
            mid_y += (Math.random()-.5)*displace;
            this.drawLightning(x1,y1,mid_x,mid_y,displace/2);
            this.drawLightning(x2,y2,mid_x,mid_y,displace/2);
        }
    }
}


